﻿namespace CommunicationDemo
{
    using System;
    using System.Reactive.Linq;
    using System.Reactive.Subjects;
    using Resources;
    using WP7Contrib.Communications;

    public class WeatherService : IProviderWeather
    {
        private readonly IHandleResources weatherResource;

        public WeatherService(IHandleResourcesFactory handlerFactory)
        {
            weatherResource = handlerFactory.Create()
                .ForType(ResourceType.Xml)
                .UseUrlForGet("http://www.google.com/ig/api?weather={0}");
        }

        public IObservable<WeatherSummary> Get(string location)
        {
            try
            {
                var observable = new Subject<WeatherSummary>();
                this.weatherResource.Get<xml_api_reply>(location)
                    .ObserveOnDispatcher()
                    .Subscribe(response =>
                                    {
                                        var weather = ProcessResponse(response);
                                        observable.OnNext(weather);
                                    },
                                observable.OnError,
                                observable.OnCompleted);

                return observable;
            }
            catch (Exception exn)
            {
                throw new Exception("Failed to get Weather!", exn);
            }
        }

        private WeatherSummary ProcessResponse(xml_api_reply response)
        {
            var summary = new WeatherSummary();
            summary.Current = new Weather();
            summary.Current.Temperature = Convert.ToInt32(response.weather[0].current_conditions[0].temp_c[0].data);

            return summary;
        }
    }
}